package com.cskaoyan.aop;

import com.cskaoyan.dao.adminmanage.LogMapper;
import com.cskaoyan.model.BaseRespVo;
import com.cskaoyan.model.admin.adminmanage.log.LogMessagePOJO;
import com.cskaoyan.model.realm.AdminLoginAdminData;
import com.cskaoyan.utils.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @Author:
 * @description:
 * @keypoint:
 * @tags:
 * @related:
 */

@Configuration
@Aspect
public class LogAspect {

    @Autowired
    LogMapper logMapper;


    @Autowired
    HttpServletRequest req;

    @Pointcut("execution(* com.cskaoyan.controller.admin..*(..))")
    public void servicePointCut() {
    }

//    @Around(value = "servicePointCut()")
//    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
//        //方法的执行
//        BaseRespVo proceed = (BaseRespVo) proceedingJoinPoint.proceed();
//
//
//        return proceed;
//    }

    @AfterReturning(value = "servicePointCut()", returning = "returnValue")
    public void afterReturning(Object returnValue) {
        insertLog(true);
    }

    @AfterThrowing(value = "servicePointCut()", throwing = "e")
    public void afterThrowing(Throwable e) {
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("resultValue", e.getMessage());
        insertLog(false);
    }


    public void insertLog(Boolean returnStatus) {

        String op = req.getServletPath(); // /admin/xxx/xxx
        String[] split = op.split("/");
        String s = split[split.length - 1];
        if (!s.equals("list") && !s.equals("options") && !req.getMethod().equals("OPTIONS")) {

            LogMessagePOJO logMessagePOJO = new LogMessagePOJO();
            logMessagePOJO.setDeleted(false);

            Subject subject = SecurityUtils.getSubject();
            //获取admin信息
            AdminLoginAdminData principal = (AdminLoginAdminData) subject.getPrincipal();
            String adminName = principal.getUsername();
            logMessagePOJO.setAdmin(adminName);
            //获取ip信息
            String ip = principal.getLast_login_ip();
            logMessagePOJO.setIp(ip);
//            String id = session.getId();
            //获取时间
            Date time = DateUtils.getNowDate();
            logMessagePOJO.setAdd_time(time);
            logMessagePOJO.setUpdate_time(time);

            //当前的admin的角色是不是管理员
            Boolean ifSuperAdmin = false;
            Integer[] roleIds = principal.getRoleIds();
            for (Integer roleId : roleIds) {
                if (roleId == 1) {
                    ifSuperAdmin = true;
                }
            }

            //获取操作类别
            if (op.contains("order")) { //订单操作
                logMessagePOJO.setType(2);
            } else {
                if (ifSuperAdmin) { //如果是超级管理员，那么是安全的操作
                    logMessagePOJO.setType(1);
                } else if (op.contains("index")) { // 其他，例如权限测试
                    logMessagePOJO.setType(3);
                } else {
                    logMessagePOJO.setType(0); //一般操作
                }
            }
            //获取操作动作

//        Object aThis = proceedingJoinPoint.getThis();
//            Object target = proceedingJoinPoint.getTarget();
//        Class<?> aClass = target.getClass();
//        RequestMapping annotationUrl = aClass.getAnnotation(RequestMapping.class);
//        String value = annotationUrl.value()[0];
//
//            Signature signature = proceedingJoinPoint.getSignature();
//        Method declaredMethod = aClass.getDeclaredMethod(signature.getName());
//        declaredMethod.setAccessible(true);
//        RequestMapping annotationSubUrl = declaredMethod.getAnnotation(RequestMapping.class);
//        String s = annotationSubUrl.value()[0];
//        String op = (value+s).replace("admin/","");

            //使用req获取url
            //获取操作动作 如果是list不需要去插入操作
            String label = null;
            if ("/admin/auth/login".equals(op)) {
                label = "登录";
            } else if ("/admin/auth/logout".equals(op)) {
                label = "登出";
            } else {
                String method = req.getMethod();
                String action = method + " " + op;
                label = logMapper.selectLabelByApi(action);
            }
            logMessagePOJO.setAction(label);


            //获取操作状态
            logMessagePOJO.setStatus(returnStatus);

            Session session = subject.getSession();
            //获取操作结果
            //todo 协调一下，大家把信息放session域里面？
            String resultValue = (String) session.getAttribute("resultValue");
            if (resultValue != null) {
                logMessagePOJO.setResult(resultValue);
            }

            //获取备注
            //todo


//        System.out.println("insert into log");
            Integer result = logMapper.insertLog(logMessagePOJO);
        }
    }

}
